import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  OnDestroy
} from "@angular/core";
import { ManagementBean } from "./bean/management.bean";
import { UploadFile, NzNotificationService } from "ng-zorro-antd";
import { HttpServcie } from "../../../service/http.service";
import { Config } from "../../../service/config";
import {Router} from "@angular/router";

@Component({
  selector: "elevator-safe-management",
  templateUrl: "./elevator-safe-management.html",
  styleUrls: ["./elevator-safe-management.scss"]
})
export class ElevatorSafeManagementComponent implements OnInit, OnDestroy {
  uploadUrl = Config.IP + Config.API.upload; //上传的地址
  managementBean = new ManagementBean();
  elevatorNum; //电梯编号
  uploadParam;
  config: any = Config;
  previewImage = "";
  previewVisible = false;
  editFlag: boolean = false;
  sysUser;
  orgId;

  constructor(
    private _notification: NzNotificationService,
    private httpServcie: HttpServcie,
    private router: Router
  ) { }

  ngOnInit() {
    // 获取机构id
    this.sysUser = JSON.parse(window.localStorage.getItem("user"));
    this.orgId = this.sysUser.partyId;
    console.log(this.orgId);

    this.eleSafeManageQuery(this.orgId);
  }

  ngOnDestroy() {
    //如果页面被编辑过，则执行保存操作，防止删除图片与数据库不同步
    if (this.editFlag) {
      this.saveEdit();
    }
  }
  toTrainingData(){
    this.router.navigate([
      "/home/training-result",
    ]);
  }
  // 保存
  saveEdit() {
    //必传项非空检验
    let flag = false;
    // if (
    //   !this.managementBean.esms.length ||
    //   !this.managementBean.lcso.length ||
    //   !this.managementBean.lase.length ||
    //   !this.managementBean.laes.length ||
    //   !this.managementBean.rses.length ||
    //   !this.managementBean.ess.length ||
    //   !this.managementBean.edis.length ||
    //   !this.managementBean.ms.length ||
    //   !this.managementBean.erir.length ||
    //   !this.managementBean.lsht.length ||
    //   !this.managementBean.tes.length ||
    //   !this.managementBean.esfs.length ||
    //   !this.managementBean.mdla.length ||
    //   !this.managementBean.eits.length ||
    //   !this.managementBean.kmr.length ||
    //   !this.managementBean.rmmr.length ||
    //   !this.managementBean.sore.length ||
    //   !this.managementBean.eerp.length ||
    //   !this.managementBean.rere.length
    // ) {
    //   flag = true;
    // }
    if (flag) {
      return this._notification.create(
        "warning",
        "警告提示",
        "抱歉! 带*为必传项，请您务必补充完整信息"
      );
    } else {
      this.uploadParam = Object.assign({}, this.managementBean);
      //格式化bean中参数，只上传url地址
      for (let i in this.managementBean) {
        let arr = [];
        if (this.managementBean[i].length) {
          for (let k of this.managementBean[i]) {
            if (k.status == "done") {
              // 回调的图片处理
              if (k["url"]) {
                let url = `${k.name}`;
                arr.push(url);
              } else {
                let url = `${k["response"].data}`;
                arr.push(url);
              }
              // 上传的图片处理
            }
          }
          this.uploadParam[i] = JSON.stringify(arr);
        } else {
          this.uploadParam[i] = "";
        }
      }
      this.uploadParam.orgId = this.orgId;
      let users = JSON.parse(window.localStorage.getItem("user"));

      this.uploadParam.loggerType = users.partyType;
      //当前机构的类型
      this.uploadParam.loggerPartyId = users.partyId;

      this.uploadParam.roleId = users.roleId;

      this.uploadParam.loggerUserId = users.id;

      this.httpServcie.eleSafeManageUpLoad(this.uploadParam).subscribe(data => {
        if (data.status == 200) {
          this._notification.create("success", "成功提示", "保存成功");
        } else {
          this._notification.create("error", "失败提示", data.message);
          return;
        }
      });
    }
  }

  // 初始化查询
  eleSafeManageQuery(param) {
    this.httpServcie.eleSafeManageQuery(param).subscribe(data => {
      if (data.status == 200) {
        this.handleData(data);
      } else {
        this._notification.create("error", "失败提示", data.message);
        return;
      }
    });
  }

  // 查询回显图片格式解析
  handleData(data) {
    let ret = data.data.list;
    let arr = [];
    for (let i in ret) {
      this.managementBean[i] = [];
      if (ret[i] != "[]" && ret[i] != "") {
        let arr = JSON.parse(ret[i]);
        for (let j of arr) {
          let uid = new Date();
          this.managementBean[i].push({
            uid: uid.getTime(),
            name: j,
            status: "done",
            url: `${this.config.IP + this.config.API.getUpload}${j}`
          });
        }
      }
    }
  }

  // 移除图片
  nzRemoveFile = (file: UploadFile) => {
    let fileItem = file;
    if (fileItem["status"] == "removed") {
      if (fileItem["url"] && fileItem["url"].includes("http")) {
        this.deleteImg(fileItem.name);
      } else {
        this.deleteImg(fileItem["response"]["data"]);
      }
    }
  };
  // 删除图片服务
  deleteImg(filedata) {
    this.httpServcie.deleteUpload(filedata).subscribe(
      data => {
        if (data["status"] != "200") {
          this._notification.create("error", "错误提示", "删除失败！");
          return;
        }
        for (let i in this.managementBean) {
          if (this.managementBean[i].length) {
            if (
              this.managementBean[i].length == 1 &&
              this.managementBean[i][0].status == "removed"
            ) {
              this.managementBean[i] = [];
            } else {
              let list = [];
              this.managementBean[i].forEach((element, idx) => {
                if (element["status"] == "removed") {
                  this.managementBean[i].splice(idx, 1);
                  this.managementBean[i] = this.managementBean[i];
                  list = this.managementBean[i];
                  this.managementBean[i] = [];
                }
              });
              list.forEach(element => {
                this.managementBean[i].push(element);
              });
            }
          }
        }
        this.editFlag = true;
        let param = {
          type: '2',
          partyId: this.sysUser.partyId,
          empiricValue: '-5',
          content: '删除1份电梯安全管理制度中的资料'
        }
        this.httpServcie.addByUpload(param).subscribe(data => {

        }, err => {

        })
      },
      error => {
        this._notification.create("error", "错误提示", "请求超时！");
        return;
      }
    );
  }

  // 预览图片
  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  };
  /**
   * 查找指定字符所在的位置
   * @param str
   * @param cha
   * @param num
   */
  find(str, cha, num) {
    let x = str.indexOf(cha);
    for(let i = 0; i < num; i++) {
      x = str.indexOf(cha, x + 1);
    }
    return x;
  }

  nzChange(event) {
    if (event.file.status == "error") {
      this._notification.blank("上传失败", `${event.file.message}`);
    }
    if (event.file.status == "done") {
      this.editFlag = true;
      let param = {
        type: '2',
        partyId: this.sysUser.partyId,
        empiricValue: '5',
        content: '上传1份电梯安全管理制度中的资料'
      }
      this.httpServcie.addByUpload(param).subscribe(data => {

      }, err => {

      })
    }
  }
}
